#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
创建简单的MES应用
"""
import os

def create_mes_app():
    """创建MES应用目录和文件"""
    
    # 创建应用目录
    app_dir = "simple_mes"
    if not os.path.exists(app_dir):
        os.makedirs(app_dir)
        print(f"✅ 创建应用目录: {app_dir}")
    
    # 创建 __init__.py
    with open(f"{app_dir}/__init__.py", "w", encoding="utf-8") as f:
        f.write("")
    
    # 创建 apps.py
    with open(f"{app_dir}/apps.py", "w", encoding="utf-8") as f:
        f.write("""from django.apps import AppConfig

class SimpleMesConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'simple_mes'
    verbose_name = 'MES系统'
""")
    
    # 创建 models.py
    with open(f"{app_dir}/models.py", "w", encoding="utf-8") as f:
        f.write("""# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User

class Customer(models.Model):
    \"\"\"客户管理\"\"\"
    name = models.CharField("客户名称", max_length=100)
    code = models.CharField("客户编码", max_length=50, unique=True)
    contact = models.CharField("联系人", max_length=50, blank=True)
    phone = models.CharField("电话", max_length=20, blank=True)
    email = models.EmailField("邮箱", blank=True)
    address = models.TextField("地址", blank=True)
    created_at = models.DateTimeField("创建时间", auto_now_add=True)
    
    class Meta:
        verbose_name = "客户"
        verbose_name_plural = "客户管理"
    
    def __str__(self):
        return f"{self.name} ({self.code})"

class Product(models.Model):
    \"\"\"产品管理\"\"\"
    name = models.CharField("产品名称", max_length=100)
    code = models.CharField("产品编码", max_length=50, unique=True)
    category = models.CharField("产品类别", max_length=50, blank=True)
    description = models.TextField("产品描述", blank=True)
    unit = models.CharField("单位", max_length=10, default="件")
    price = models.DecimalField("单价", max_digits=10, decimal_places=2, null=True, blank=True)
    created_at = models.DateTimeField("创建时间", auto_now_add=True)
    
    class Meta:
        verbose_name = "产品"
        verbose_name_plural = "产品管理"
    
    def __str__(self):
        return f"{self.name} ({self.code})"

class Order(models.Model):
    \"\"\"订单管理\"\"\"
    STATUS_CHOICES = [
        ('pending', '待处理'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]
    
    order_no = models.CharField("订单号", max_length=50, unique=True)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name="客户")
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="产品")
    quantity = models.PositiveIntegerField("数量")
    status = models.CharField("状态", max_length=20, choices=STATUS_CHOICES, default='pending')
    order_date = models.DateTimeField("下单时间", auto_now_add=True)
    delivery_date = models.DateField("交货日期", null=True, blank=True)
    notes = models.TextField("备注", blank=True)
    
    class Meta:
        verbose_name = "订单"
        verbose_name_plural = "订单管理"
        ordering = ['-order_date']
    
    def __str__(self):
        return f"{self.order_no} - {self.customer.name}"

class Equipment(models.Model):
    \"\"\"设备管理\"\"\"
    STATUS_CHOICES = [
        ('running', '运行中'),
        ('maintenance', '维护中'),
        ('idle', '空闲'),
        ('fault', '故障'),
    ]
    
    name = models.CharField("设备名称", max_length=100)
    code = models.CharField("设备编码", max_length=50, unique=True)
    model = models.CharField("设备型号", max_length=50, blank=True)
    location = models.CharField("设备位置", max_length=100, blank=True)
    status = models.CharField("设备状态", max_length=20, choices=STATUS_CHOICES, default='idle')
    purchase_date = models.DateField("采购日期", null=True, blank=True)
    last_maintenance = models.DateField("上次维护", null=True, blank=True)
    notes = models.TextField("备注", blank=True)
    
    class Meta:
        verbose_name = "设备"
        verbose_name_plural = "设备管理"
    
    def __str__(self):
        return f"{self.name} ({self.code})"

class Employee(models.Model):
    \"\"\"员工管理\"\"\"
    DEPARTMENT_CHOICES = [
        ('production', '生产部'),
        ('quality', '质量部'),
        ('warehouse', '仓库'),
        ('management', '管理部'),
        ('maintenance', '维护部'),
    ]
    
    name = models.CharField("姓名", max_length=50)
    employee_id = models.CharField("工号", max_length=20, unique=True)
    department = models.CharField("部门", max_length=20, choices=DEPARTMENT_CHOICES)
    position = models.CharField("职位", max_length=50, blank=True)
    phone = models.CharField("电话", max_length=20, blank=True)
    email = models.EmailField("邮箱", blank=True)
    hire_date = models.DateField("入职日期", null=True, blank=True)
    is_active = models.BooleanField("是否在职", default=True)
    
    class Meta:
        verbose_name = "员工"
        verbose_name_plural = "员工管理"
    
    def __str__(self):
        return f"{self.name} ({self.employee_id})"

class WorkOrder(models.Model):
    \"\"\"工单管理\"\"\"
    STATUS_CHOICES = [
        ('created', '已创建'),
        ('assigned', '已分配'),
        ('in_progress', '进行中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]
    
    work_order_no = models.CharField("工单号", max_length=50, unique=True)
    order = models.ForeignKey(Order, on_delete=models.CASCADE, verbose_name="关联订单")
    assigned_to = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="负责人")
    equipment = models.ForeignKey(Equipment, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="使用设备")
    status = models.CharField("状态", max_length=20, choices=STATUS_CHOICES, default='created')
    start_date = models.DateTimeField("开始时间", null=True, blank=True)
    end_date = models.DateTimeField("结束时间", null=True, blank=True)
    notes = models.TextField("备注", blank=True)
    created_at = models.DateTimeField("创建时间", auto_now_add=True)
    
    class Meta:
        verbose_name = "工单"
        verbose_name_plural = "工单管理"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.work_order_no} - {self.order.product.name}"
""")
    
    # 创建 admin.py
    with open(f"{app_dir}/admin.py", "w", encoding="utf-8") as f:
        f.write("""# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Customer, Product, Order, Equipment, Employee, WorkOrder

@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'contact', 'phone', 'created_at']
    list_filter = ['created_at']
    search_fields = ['name', 'code', 'contact']
    readonly_fields = ['created_at']

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'category', 'unit', 'price', 'created_at']
    list_filter = ['category', 'created_at']
    search_fields = ['name', 'code', 'category']
    readonly_fields = ['created_at']

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ['order_no', 'customer', 'product', 'quantity', 'status', 'order_date']
    list_filter = ['status', 'order_date']
    search_fields = ['order_no', 'customer__name', 'product__name']
    readonly_fields = ['order_date']
    date_hierarchy = 'order_date'

@admin.register(Equipment)
class EquipmentAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'model', 'location', 'status', 'last_maintenance']
    list_filter = ['status', 'location']
    search_fields = ['name', 'code', 'model']

@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
    list_display = ['name', 'employee_id', 'department', 'position', 'is_active']
    list_filter = ['department', 'is_active', 'hire_date']
    search_fields = ['name', 'employee_id', 'position']

@admin.register(WorkOrder)
class WorkOrderAdmin(admin.ModelAdmin):
    list_display = ['work_order_no', 'order', 'assigned_to', 'equipment', 'status', 'created_at']
    list_filter = ['status', 'created_at', 'assigned_to__department']
    search_fields = ['work_order_no', 'order__order_no', 'assigned_to__name']
    readonly_fields = ['created_at']
    date_hierarchy = 'created_at'
""")
    
    # 创建 views.py
    with open(f"{app_dir}/views.py", "w", encoding="utf-8") as f:
        f.write("""# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import JsonResponse
from .models import Customer, Product, Order, Equipment, Employee, WorkOrder

def dashboard(request):
    \"\"\"仪表板视图\"\"\"
    context = {
        'total_customers': Customer.objects.count(),
        'total_products': Product.objects.count(),
        'total_orders': Order.objects.count(),
        'total_equipment': Equipment.objects.count(),
        'total_employees': Employee.objects.count(),
        'active_work_orders': WorkOrder.objects.filter(status__in=['created', 'assigned', 'in_progress']).count(),
    }
    return render(request, 'simple_mes/dashboard.html', context)

def api_stats(request):
    \"\"\"API统计数据\"\"\"
    data = {
        'customers': Customer.objects.count(),
        'products': Product.objects.count(),
        'orders': Order.objects.count(),
        'equipment': Equipment.objects.count(),
        'employees': Employee.objects.count(),
        'work_orders': WorkOrder.objects.count(),
    }
    return JsonResponse(data)
""")
    
    # 创建 urls.py
    with open(f"{app_dir}/urls.py", "w", encoding="utf-8") as f:
        f.write("""# -*- coding: utf-8 -*-
from django.urls import path
from . import views

app_name = 'simple_mes'

urlpatterns = [
    path('', views.dashboard, name='dashboard'),
    path('api/stats/', views.api_stats, name='api_stats'),
]
""")
    
    # 创建模板目录
    template_dir = f"{app_dir}/templates/simple_mes"
    if not os.path.exists(template_dir):
        os.makedirs(template_dir)
    
    # 创建仪表板模板
    with open(f"{template_dir}/dashboard.html", "w", encoding="utf-8") as f:
        f.write("""<!DOCTYPE html>
<html>
<head>
    <title>MES系统仪表板</title>
    <meta charset="utf-8">
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .header { background: #2c3e50; color: white; padding: 20px; margin-bottom: 20px; }
        .stats { display: flex; flex-wrap: wrap; gap: 20px; }
        .stat-card { 
            background: #ecf0f1; 
            padding: 20px; 
            border-radius: 5px; 
            min-width: 200px;
            text-align: center;
        }
        .stat-number { font-size: 2em; font-weight: bold; color: #3498db; }
        .stat-label { color: #7f8c8d; margin-top: 10px; }
        .nav { margin: 20px 0; }
        .nav a { 
            display: inline-block; 
            padding: 10px 20px; 
            background: #3498db; 
            color: white; 
            text-decoration: none; 
            margin-right: 10px;
            border-radius: 3px;
        }
        .nav a:hover { background: #2980b9; }
    </style>
</head>
<body>
    <div class="header">
        <h1>🏭 MES制造执行系统</h1>
        <p>欢迎使用制造执行系统管理平台</p>
    </div>
    
    <div class="nav">
        <a href="/admin/">管理后台</a>
        <a href="/simple_mes/">仪表板</a>
        <a href="/simple_mes/api/stats/">API数据</a>
    </div>
    
    <h2>📊 系统概览</h2>
    <div class="stats">
        <div class="stat-card">
            <div class="stat-number">{{ total_customers }}</div>
            <div class="stat-label">客户总数</div>
        </div>
        <div class="stat-card">
            <div class="stat-number">{{ total_products }}</div>
            <div class="stat-label">产品总数</div>
        </div>
        <div class="stat-card">
            <div class="stat-number">{{ total_orders }}</div>
            <div class="stat-label">订单总数</div>
        </div>
        <div class="stat-card">
            <div class="stat-number">{{ total_equipment }}</div>
            <div class="stat-label">设备总数</div>
        </div>
        <div class="stat-card">
            <div class="stat-number">{{ total_employees }}</div>
            <div class="stat-label">员工总数</div>
        </div>
        <div class="stat-card">
            <div class="stat-number">{{ active_work_orders }}</div>
            <div class="stat-label">活跃工单</div>
        </div>
    </div>
    
    <h2>🔧 快速操作</h2>
    <div class="nav">
        <a href="/admin/simple_mes/customer/add/">添加客户</a>
        <a href="/admin/simple_mes/product/add/">添加产品</a>
        <a href="/admin/simple_mes/order/add/">创建订单</a>
        <a href="/admin/simple_mes/equipment/add/">添加设备</a>
        <a href="/admin/simple_mes/employee/add/">添加员工</a>
        <a href="/admin/simple_mes/workorder/add/">创建工单</a>
    </div>
    
    <h2>📋 业务模块</h2>
    <div class="nav">
        <a href="/admin/simple_mes/customer/">客户管理</a>
        <a href="/admin/simple_mes/product/">产品管理</a>
        <a href="/admin/simple_mes/order/">订单管理</a>
        <a href="/admin/simple_mes/equipment/">设备管理</a>
        <a href="/admin/simple_mes/employee/">员工管理</a>
        <a href="/admin/simple_mes/workorder/">工单管理</a>
    </div>
</body>
</html>""")
    
    print("✅ MES应用创建完成！")
    print(f"📁 应用目录: {app_dir}")
    print("📋 包含以下功能:")
    print("  - 客户管理")
    print("  - 产品管理") 
    print("  - 订单管理")
    print("  - 设备管理")
    print("  - 员工管理")
    print("  - 工单管理")
    print("  - 仪表板视图")

if __name__ == "__main__":
    create_mes_app() 